package com.partners.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.partners.configure.wechatmp.WxMpProperties;
import com.partners.constant.ErrorMessageEnum;
import com.partners.dao.basic.ConfigDao;
import com.partners.dao.basic.CustomerDao;
import com.partners.dao.basic.UserDao;
import com.partners.dao.bo.ConfigDO;
import com.partners.dao.bo.CustomerDO;
import com.partners.dao.bo.UserDO;
import com.partners.dao.dto.CustomerOutputDTO;
import com.partners.model.BusinessException;
import com.partners.model.Paging;
import com.partners.service.CustomerService;
import com.partners.service.UploadFileService;
import com.partners.utils.CodeUtils;
import com.partners.utils.JsonUtils;
import com.partners.utils.TimestampUtils;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.javassist.bytecode.LineNumberAttribute;
import org.bouncycastle.util.Times;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Time;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author liangyongle
 * @date 2018-12-11
 */
@Service
@Slf4j
public class CustomerServiceImpl implements CustomerService {

    @Resource
    private WxMpProperties wxMpProperties;

    @Resource
    private CustomerDao customerDao;

    @Resource
    private UserDao userDao;

    @Resource
    private UploadFileService uploadFileService;

    @Resource
    private ConfigDao configDao;


    /**
     * 获取客户列表
     * @param paging Paging //分页数
     *        name String  //名字
     *        phone Integer  //电话号码
     *        uid Integer 按合伙人查询
     * @return List
     */
    @Override
    public Map<String,Object> getCustomerList(Paging paging,Integer returnType, String name, BigInteger phone, Integer uid) {
        PageHelper.startPage(paging.getPage(),paging.getRows());
        Map<String,Object> allList = new HashMap<>();
        List<Map<String,Object>> list =  customerDao.getCustomerListSelective(name,phone,uid);
        String status  = "";
        Integer overTime = 0;
        Integer nowTime = TimestampUtils.timestamp();
        for (Map<String,Object> map : list){
            if((Integer) map.get("verification") == 1){
                //已经核销
                status = "已核销";
            }else if(map.get("openid").equals("")){
                status = "待领券";
            }else if((nowTime - (Integer) map.get("addtime"))/3600/24 > 7){
                status = "已过期";
            }else{
                overTime = 7-(nowTime - (Integer) map.get("addtime"))/3600/24;
                status = "已领券";
            }
            map.put("status",status);
            map.put("overTime",overTime);
            //处理时间搓
            String timeFormat = "yyyy-MM-dd hh:mm:ss";
            String addtime = TimestampUtils.getDateTimeOfTimestamp((Integer) map.get("addtime"),timeFormat);
            String dateFormat = "yyyy-MM";
            String format = TimestampUtils.getDateTimeOfTimestamp((Integer) map.get("addtime"),dateFormat);
            map.put("addtime",addtime);
            map.put("format",format);
        }
        PageInfo page = new PageInfo(list);
        Object total = page.getTotal();
        allList.put("total",total);
        if(returnType == 1){
            final Map<Object, List<Map<String, Object>>> timeList = list.stream().collect(Collectors.groupingBy(i -> i.get("format")));
            TreeMap<Object, List<Map<String, Object>>> treeMap = new TreeMap<>();
            treeMap.putAll(timeList);
            NavigableMap<Object, List<Map<String, Object>>> descendingMap = treeMap.descendingMap();
            allList.put("list",descendingMap);
        }else{
            allList.put("list",list);
        }
        return allList;

    }


    /**
     * 客户领取优惠券
     * @param Id Integer
     * @return List
     */
    @Override
    @Transactional
    public void getCustomerCoupon(Integer Id) {
      //查询客户是否存在
      //是否已经领取过
      CustomerDO customerDO = customerDao.selectByPrimaryKey(Id);
      if(customerDO == null){
          throw  BusinessException.of(ErrorMessageEnum.CUSTOMER_NOT_FOUND);
      }
      if(customerDO.getGettime() != 0){
          throw BusinessException.of(ErrorMessageEnum.COUPON_IS_GET);
      }
      CustomerDO customer = new CustomerDO();
      customer.setId(Id);
      customer.setGettime(TimestampUtils.timestamp());
      customerDao.updateByPrimaryKeySelective(customer);
    }



    /**
     * 获取优惠券信息
     * @param Id Integer
     * @return List
     */
    @Override
    public Map<String, Object> getCustomerCouponDetail(Integer Id) {
        Map<String,Object> detail = customerDao.getCustomerCouponDetail(Id);
        String timeFormat = "yyyy-MM-dd hh:mm:ss";
        Integer status = 0; //未使用
        if((Integer) detail.get("overtime") < TimestampUtils.timestamp()){
            status = 1; //已过期
        }
        if((Integer) detail.get("verification") ==1){
            status = 2; //已核销
        }
        String overtime = TimestampUtils.getDateTimeOfTimestamp((Integer) detail.get("overtime"),timeFormat);
        String gettime = TimestampUtils.getDateTimeOfTimestamp((Integer) detail.get("gettime"),timeFormat);
        detail.put("overtime",overtime);
        detail.put("gettime",gettime);
        detail.put("status",status);
        return detail;
    }


    /**
     * 获取客户详情
     * @param Id Integer
     * @return List
     */
    @Override
    public CustomerOutputDTO getCustomerDetail(Integer Id) {
        CustomerOutputDTO detail = customerDao.getCustomerDetailById(Id);
        String status  = "待领券";
        Integer overTime = 0;
        Integer nowTime = TimestampUtils.timestamp();
        if(detail.getVerification() == 1){
            status = "已使用";
        }else if(Integer.parseInt(detail.getOvertime()) < TimestampUtils.timestamp() ){
            status = "已过期";
        }else if(detail.getGettime().equals("0")){
            status = "待领券";
        }else{
            status = "已失效";
        }

        detail.setStatus(status);
        String dateFormat = "yyyy-MM-dd HH:mm:ss";
        String addtime = TimestampUtils.getDateTimeOfTimestamp(Integer.parseInt(detail.getAddtime()),dateFormat);
        String gettime = "0";
        if(Integer.parseInt(detail.getGettime()) >0){
            gettime = TimestampUtils.getDateTimeOfTimestamp(Integer.parseInt(detail.getGettime()),dateFormat);
        }
        detail.setGettime(gettime);
        detail.setAddtime(addtime);
        return detail;
    }



    /**
     * 编辑客户
     * @param customerDo CustomerDO
     * @return List
     */
    @Override
    @Transactional
    public Integer editCustomer(CustomerDO customerDo) {
        //排除重复
        if(customerDo.getUid() != null){
            Integer exist = customerDao.getUserCustomerByPhone(customerDo.getPhone(),customerDo.getUid());
            if(exist != null){
                throw BusinessException.of(ErrorMessageEnum.PHONE_IS_EXIST);
            }
        }
        String baseUrl = wxMpProperties.getBaseUrl();
        Integer result = 0;
        if(customerDo.getId() !=null){
            //编辑客户
            String url = baseUrl+"/customerPage/scan_code?customer_id="+customerDo.getId();
            String qrcode = uploadFileService.createQrcode(url);
            customerDo.setQrcode(qrcode);
            result = customerDao.updateByPrimaryKeySelective(customerDo);
        }else{
            //新增客户
            //先查询当前业务员下面的客户最大的code
            Long customerLastCoder = customerDao.getCustomerLastCode(customerDo.getUid());
            String  newCode = "";
            if(customerLastCoder != null){
                    newCode = CodeUtils.getNextCustomerCode(customerLastCoder);
            }else{
                //获取该客户的业务员的code
               UserDO user = userDao.selectByPrimaryKey(customerDo.getUid());
               Long code = user.getCode().longValue();
               newCode = CodeUtils.getNewCustomerCode(code);

            }

            customerDo.setCode(Long.parseLong(newCode));
            customerDo.setAddtime(TimestampUtils.timestamp());
            //生成二维码
            //查询当前设置
            ConfigDO configDO = configDao.selectByPrimaryKey(1);
            customerDo.setDiscountType(configDO.getDiscountType());
            customerDo.setDiscount(configDO.getDiscount());
            customerDo.setFull(configDO.getFull());
            //写入过期时间
            Integer overTime = TimestampUtils.timestamp()+configDO.getIndate()*86400;
            customerDo.setOvertime(overTime);
            //插入数据返回id
            customerDao.insertSelective(customerDo);
            Integer newId = customerDo.getId();
            String url = baseUrl+"/customerPage/scan_code?customer_id="+newId;
            CustomerDO customer = new CustomerDO();
            String qrcode = uploadFileService.createQrcode(url);
            customer.setQrcode(qrcode);
            customer.setId(newId);
            result =customerDao.updateByPrimaryKeySelective(customer);
        }
        return result;
    }

    /**
     * 删除客户
     * @param id Integer
     * @return List
     */
    @Override
    public Integer CustomerDelete(Integer id) {
       CustomerOutputDTO detail = customerDao.getCustomerDetailById(id);
       if(detail == null){
           throw BusinessException.of(ErrorMessageEnum.RECORD_NOT_FOUND);
       }
       Integer result =  customerDao.deleteByPrimaryKey(id);
       return result;
    }


    /**
     * 获取客户的编号
     * @param id Integer
     * @return List
     */
    @Override
    public Map<String, Object> getCustomerCode(Integer id) {
        UserDO user = userDao.selectByPrimaryKey(id);
        Integer userCode = user.getCode();
        String code = CodeUtils.getNewUserCode(userCode);
        Map<String,Object> result = new HashMap<>();
        result.put("code",code);
        return result;
    }

    /**
     * 扫描二维码操作
     * @param id Integer
     * @return List
     */
    @Override
    public Integer scanCode(HttpSession session, Integer id) {
        Object fans = session.getAttribute("openId");
        Integer type = 0; //状态 1:领取成功 /2:已经领取 /3:无权限操作 /4：已过期
        CustomerOutputDTO customerDetail = getCustomerDetail(id);
        if(customerDetail == null){
            type= 0; //无效的二维码
        }
        if(fans !=null){
            JSONObject info = JSON.parseObject(JsonUtils.toJson(fans));
            log.info("info:{}",info);
            Integer nowTime = TimestampUtils.timestamp();
            String openId = info.getString("openid");
            Integer fansType = info.getInteger("type");
            if(fansType ==0){
                //粉丝(提示没权限)
                type = 3; //无权限操作
            }else{
                //新粉丝(自动绑定)
                if(Integer.parseInt(customerDetail.getGettime()) < TimestampUtils.timestamp()){
                    type = 4;//已过期
                }else if(!customerDetail.getGettime().equals("0")){
                    type = 2;//已领取
                }
            }
        }
        return type;
    }


    /**
     * 获取客户二维码
     * @param id Integer
     * @return List
     */
    @Override
    public Map<String, Object> getCustomerQrCode(Integer id) {
        Map<String,Object> qrcode =  customerDao.getCustomerQrCode(id);
        qrcode.put("code",qrcode.get("code").toString());
        return qrcode;
    }


    /**
     * 选择已报备的业主列表
     * @param paging Paging
     *        name String
     *        phone integer
     * @return List
     */
    @Override
    public Map<String, Object> selectCustomerList(Paging paging, String name, BigInteger phone) {
        PageHelper.startPage(paging.getPage(),paging.getRows());
        Map<String,Object> allList = new HashMap<>();
        Integer nowtime = TimestampUtils.timestamp();
        List<CustomerOutputDTO> list =  customerDao.selectCustomerList(nowtime,name,phone);
        for (CustomerOutputDTO map:list){
            String timeFormat = "yyyy-MM-dd HH:mm:ss";
            String addtime = TimestampUtils.getDateTimeOfTimestamp(Integer.parseInt(map.getAddtime()),timeFormat);
            map.setAddtime(addtime);
        }
        PageInfo page = new PageInfo(list);
        Object total = page.getTotal();
        allList.put("total",total);
        allList.put("list",list);
        return allList;
    }

    /**
     * 核销优惠券
     * @param id  Integer uid Integer
     * @return boolean
     * */
    @Override
    @Transactional
    public void verificateCoupon(Integer id, Integer uid, Float saleMoney) {
         //1.查询该优惠券是会否存在
        //2.是否已经使用或者过期
        Integer nowTime = TimestampUtils.timestamp();
        CustomerDO customerDO = customerDao.selectByPrimaryKey(id);
        //不存在
        if(customerDO == null){
            throw  BusinessException.of(ErrorMessageEnum.COUPON_NOT_FOUND);
        }
        //已使用
        if(customerDO.getVerification() == 1){
            throw  BusinessException.of(ErrorMessageEnum.COUPON_IS_USERED);
        }
        //过期
        if(customerDO.getOvertime() < nowTime){
            throw  BusinessException.of(ErrorMessageEnum.COUPON_IS_OVER);
        }
        //判断是否满足金额
        if(customerDO.getFull() >saleMoney){
            throw  BusinessException.of(ErrorMessageEnum.MONEY_NOT_ENOUTH);
        }

        CustomerDO customer = new CustomerDO();
        customer.setId(id);
        Byte ver = 1;
        customer.setVerification(ver);
        customer.setVerId(uid);
        customer.setSaleMoney(BigDecimal.valueOf(saleMoney));
        customerDao.updateByPrimaryKeySelective(customer);
    }


    /**
     * 获取所有成交用户列表
     * @param uid  Integer uid Integer
     * @return boolean
     * */
    @Override
    public Map<String, Object> getOrderCustomerList(Integer uid, Paging paging) {
        PageHelper.startPage(paging.getPage(),paging.getRows());
        Map<String,Object> allList = new HashMap<>();
        List<CustomerOutputDTO> list = customerDao.getOrderCustomerList();
        for (CustomerOutputDTO map:list){
            String timeFormat = "yyyy-MM-dd HH:mm:ss";
            String addtime = TimestampUtils.getDateTimeOfTimestamp(Integer.parseInt(map.getAddtime()),timeFormat);
            map.setAddtime(addtime);
            if(Integer.parseInt(map.getGettime()) !=  0){
                String gettime = TimestampUtils.getDateTimeOfTimestamp(Integer.parseInt(map.getGettime()),timeFormat);
                map.setGettime(gettime);
            }
        }
        PageInfo page = new PageInfo(list);
        Object total = page.getTotal();
        allList.put("total",total);
        allList.put("list",list);
        return allList;
    }


    /**
     * 获取客户记录
     * @Param id Integer id
     * @return List
     */
    @Override
    public Map<String, Object> getOrderCustomerLog(Integer id) {

        return null;
    }

    /*
    @Override
    public Map<String, Object> getQrCode(Integer id) {
        Integer uid = 2;
        ServletOutputStream stream = null;
        return null;
    }*/


}
